package com.gallsoft.games.framework.impl;

import java.util.ArrayList;
import java.util.List;

import android.view.View;

import com.gallsoft.games.framework.Pool;
import com.gallsoft.games.framework.Input.TouchEvent;
import com.gallsoft.games.framework.Pool.PoolObjectFactory;

public abstract class BaseHandler implements TouchHandler {

    List<TouchEvent> touchEvents = new ArrayList<TouchEvent>();
    List<TouchEvent> touchEventsBuffer = new ArrayList<TouchEvent>();
    Pool<TouchEvent> touchEventPool;
    float scaleX;
    float scaleY;

    public BaseHandler(View view, float scaleX, float scaleY) {
        PoolObjectFactory<TouchEvent> factory = new PoolObjectFactory<TouchEvent>() {
            public TouchEvent createObject() {
                return new TouchEvent();
            }
        };
        
        touchEventPool = new Pool<TouchEvent>(factory, 100);
        view.setOnTouchListener(this);
        
        this.scaleX = scaleX;
        this.scaleY = scaleY;        
    }
    
    /**
     * Get touch events from buffer. Synchronized as called from different
     * thread.
     * 
     * @return list of touch events in buffer
     */
    public synchronized List<TouchEvent> getTouchEvents() {
        //synchronized (this) {
            int len = touchEvents.size();
            
            for (int i = 0; i < len; i++) {
                touchEventPool.free(touchEvents.get(i));                
            }
            
            touchEvents.clear();
            touchEvents.addAll(touchEventsBuffer);
            touchEventsBuffer.clear();
            
            return touchEvents;
        //}
    }

}
